from django.shortcuts import render, redirect, get_object_or_404, HttpResponse, render_to_response
from django.views.generic import ListView
from .forms import RegisterForm, UpdateForm, LoginForm
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
import hashlib

from .models import User
from comet.models import Favorite

# Create your views here.


def register(request):
    """
    用户注册
    :param request:
    :return:
    """
    redirect_to = request.POST.get('next', request.GET.get('next', ''))
    if request.method == 'POST':
        form = RegisterForm(request.POST)

        if form.is_valid():
            stu_id = form.cleaned_data['stu_id']
            namefilter = User.objects.filter(stu_id=stu_id)
            if namefilter:
                return HttpResponse('用户已存在')
            else:
                pwd1 = form.cleaned_data['password']
                pwd2 = form.cleaned_data['password_again']
                if pwd1 == pwd2:
                    password = pwd2
                    email = form.cleaned_data['email']
                    address = form.cleaned_data['address']

                    user = User.objects.create(stu_id=stu_id, password=password, email=email, address=address)
                    user.save()

                else:
                    return render(request, 'keystone/register.html', {'error': '两次密码不一致', 'form': form})

            if redirect_to:
                return redirect(redirect_to)
            else:
                return redirect('meteor:index')

    else:
        form = RegisterForm()

    return render(request, 'keystone/register.html', context={'form': form, 'next': redirect_to})


def login(request):
    """
    用户登录
    :param request:
    :return:
    """
    redirect_to = request.POST.get('next', request.GET.get('next', ''))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            stu_id = form.cleaned_data['stu_id']
            password = form.cleaned_data['password']
            id_filter = User.objects.filter(stu_id=stu_id, password=password).all()[0]
            if id_filter:
                request.session['stu_id'] = id_filter.stu_id
            else:
                return render(request, 'keystone/register.html', {'error': '用户名或密码错误', 'form': form})

            if redirect_to:
                return redirect(redirect_to)
            else:
                return redirect('meteor:index')


        # return redirect('meteor:index')
    else:
        form = LoginForm()
        return render(request, 'keystone/login.html', context={'form': form, 'next': redirect_to})


@login_required #验证用户是否登录,登录才能更新个人信息
def update(request):
    """
    用户信息更新
    :param request:
    :return:
    """
    messages = []
    redirect_to = request.POST.get('next', request.GET.get('next', ''))

    if request.method == 'POST':

        form = UpdateForm(request.POST, request.FILES, instance=request.user)
        if form.is_valid():
            form.save()
            messages.append('信息更新成功')

            if redirect_to:
                return redirect(redirect_to)
            else:
                return redirect('/index')

    form = UpdateForm(instance=request.user)

    return render(request, 'keystone/update.html', context={'form': form, 'messages': messages, 'next': redirect_to})


def personal(request):
    return render(request, 'keystone/personal.html')

class FavoriteView(ListView):
    """
    用户收藏夹视图
    """
    model = Favorite
    template_name = 'keystone/favorite.html'
    context_object_name = 'favorite_list'

    def get_queryset(self):
        user_id = get_object_or_404(User, pk=self.kwargs.get('pk'))
        return super(FavoriteView, self).get_queryset().filter(user_id=user_id)